package com.yc.mvc.web;

import com.yc.mvc.bean.Result;
import com.yc.mvc.bean.User;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("user")
public class UserAction {
    //@RequestBody 接收 json 格式 请求体
    //不加@RequestBody, 会从请求参数中获取值
    @PostMapping("reg")
    Result req(@RequestBody @Valid User user, Errors errors){
        errors.getAllErrors();//获取所有错误
        errors.getGlobalError();//全局错误
        errors.getFieldError();//字段错误
        if (errors.hasErrors()){
            return new Result(0,"字段验证失败",errors.getFieldError());
        }
        return new Result(1,"注册成功", null);
    }

    @PostMapping("upload")
    Result upload(@RequestParam("filename")MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();//文件名
        String contentType = file.getContentType();//文件类型
        file.getSize();//文件大小
        file.transferTo((new File("F:\\Document\\123",originalFilename)));
        String webpath = "/upload/" +originalFilename;
        return  new Result(1,"文件上传成功！", webpath);
    }
}
